/*------------------------------------------------------*/
/*                                                      */
/* Copyright (C)	sky-mobi.com                        */
/* All rights reserved                                  */
/*                                                      */
/* Author   tristan.yang                                */
/*                                                      */
/* History  2011-5-20 created                           */
/*                                                      */
/*------------------------------------------------------*/

#ifndef __PS_CONNECT_H__
#define __PS_CONNECT_H__

#include "RtBase.h"
#include "RtTimeValue.h"
#include "RtUtilTemplates.h"
#include "connprovider.h"
#include "tsbase.h"
#include "skyssp_parser.h"
#include "ringbuffer.h"

class CPsConnectSink
{
public:
	// report source update info
	virtual RtResult OnLiveUpdate(const strKeyId& key, DWORD uptype, LPVOID pconn, DWORD dwchannel) = 0;
	virtual void OnReceiveLiveData(CRtMessageBlock& aData) = 0;
	virtual ~CPsConnectSink() {}
};

class CPsConnect
: public CRtTimerWrapperSink
, public IConnectionSink
, public CRtReferenceControlSingleThread
{
public:
	CPsConnect(CPsConnectSink* psink);
	virtual ~CPsConnect();
	virtual RtResult SetConnection(IConnection *pConnection);

	const CRtString& GetLiveName(){return m_strLiveName;}
	DWORD	GetChannelId(){return m_dwChannelId;}
	LPSTR	GetHeadData(DWORD& size);
	RtResult TransferHead();
	RtResult TransferData();

	static void ssp_p_callback(Int8 sFlag, Int8* pBuffer, Int32 iSize, HANDLE hHandle);
	void SetStream(t_skyssp_stream_info* streams);
protected: 
	// from CRtTimerWrapperSink
	virtual void OnTimer(CRtTimerWrapper* aID);

	// from IConnectionSink
	virtual void OnReceiveData(CRtMessageBlock& aData, IConnection* pConn);
	virtual void OnDisconnect(RtResult aReason, IConnection* pConn); 
	virtual void OnSend(IConnection* pConn);

private:
	RtResult HandleLiveInit(const CRtString& msg);
	RtResult HandleSSPHeader(const CRtString& msg);
	RtResult CheckSSPData(const CRtString& msg, DWORD& dwLen);
	RtResult CheckSSPDataEx(CRtString& msg, DWORD& dwLen);
	RtResult CheckSSPHead(CRtString& msg, DWORD& dwLen);
	LPSTR GetData(LONGLONG& sposBegin, DWORD& dwSize, BOOL& bEnd, BOOL bIFrame);
	void SaveSSPData(LPCSTR pdata, DWORD dwsize);
	void SaveRawData(LPBYTE pbuf, int isize, int iframe);

private:
    skyssp_p_handler	m_pSSPHandler;
	char				m_chSSPHead[SKYSSP_INDEX_FRAME_MAX];
	DWORD				m_dwHeadSize;
	BOOL				m_bDataError;
	BYTE				m_nAudioID;
	BYTE				m_nVideoID;
	CStreamRingBuffer*	m_pDataBuffer;
	CPacketFactory*		m_pFactory;
	LONGLONG			m_llPlayPos;

	CRtAutoPtr<IConnection> m_pConnect;
	AudienceVec			m_Audiences;

	DWORD				m_dwChannelId;
	CRtString			m_strLiveName;
	CPsConnectSink*		m_pSink;
	CRtString			m_strMsgBuf;
	Trans_Status		m_stTrans;

	DWORD				m_dwSeq;
};

#endif//__PS_CONNECT_H__
